package com.the_ring.chapter13.task;

import android.app.Activity;

import java.io.IOException;

import javax.websocket.ClientEndpoint;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;

@ClientEndpoint
public class AppClientEndpoint {

    private Activity activity;      // 声明一个活动实例
    private OnRespListener listener;    // 消息应答监听器
    private Session session;        // 连接会话

    public AppClientEndpoint(Activity activity, OnRespListener listener) {
        this.activity = activity;
        this.listener = listener;
    }

    // 向服务器发送请求报文
    public void sendRequest(String req) {
        try {
            if (session != null) {
                RemoteEndpoint.Basic remote = session.getBasicRemote();
                remote.sendText(req);   // 发送文本数据
//                remote.sendBinary(buffer); // 发送二进制数据
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 连接成功后调用
    @OnOpen
    public void onOpen(final Session session) {
        this.session = session;
    }

    // 收到服务端消息时调用
    @OnMessage
    public void processMessage(Session session, String message) {
        if (listener != null) {
            listener.receiveResponse(message);
        }
    }

    // 收到服务端错误时调用
    @OnError
    public void processError(Throwable t) {
        t.printStackTrace();
    }

    // 定义一个 WebSocket 应答的监听器接口
    public interface OnRespListener {
        void receiveResponse(String resp);
    }
}
